package org.example.controller;


import org.example.entity.User;
import org.example.service.UserImportService;
import org.example.service.UserService;
import org.example.util.ExcelUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {


    private final UserService userService;
    private final UserImportService importService;

    @Autowired
    private RedisTemplate redisTemplate;

    public UserController(UserService userService, UserImportService importService) {
        this.userService = userService;
        this.importService = importService;
    }



    @GetMapping("/test")
    public Object test() {
        int count = userService.count();
        return count;
    }



    /**
     * 数据库生成100万数据
     * @param total 总条数（默认100万）
     * @param batchSize 每批数量（默认5000）
     * @return 导入结果和耗时
     */
    @GetMapping("/geneMillion")
    public String importMillion(
            @RequestParam(defaultValue = "1000000") long total,
            @RequestParam(defaultValue = "5000") int batchSize
    ) {
        Instant start = Instant.now();
        importService.importMillionUsers(total, batchSize);
        long seconds = Duration.between(start, Instant.now()).getSeconds();
        return String.format("导入完成！总条数：%d，耗时：%d秒", total, seconds);
    }






    /**
     * 导入Excel到数据库
     */
    @PostMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 临时保存文件（EasyExcel需要文件路径）
        File tempFile = File.createTempFile("temp", file.getOriginalFilename());
        file.transferTo(tempFile);

        // 读取Excel数据
        List<User> userList = ExcelUtil.importExcel(tempFile.getAbsolutePath(), User.class);

        // 保存到数据库
        userService.batchSave(userList);

        // 删除临时文件
        tempFile.delete();
        return "导入成功，共" + userList.size() + "条数据";
    }
}